#include "gd32f30x.h"
#include "delay.h"

volatile static uint32_t delay;


void delay_init()
{
    timer_parameter_struct timer_initpara;
    rcu_periph_clock_enable(RCU_TIMER6);
    timer_deinit(TIMER6);
    timer_initpara.prescaler = (120 - 1);
    timer_initpara.alignedmode = TIMER_COUNTER_EDGE;
    timer_initpara.counterdirection = TIMER_COUNTER_UP;
    timer_initpara.period = 65535;
    timer_initpara.clockdivision = TIMER_CKDIV_DIV1;
    timer_initpara.repetitioncounter = 0;
    timer_init(TIMER6, &timer_initpara);
    timer_auto_reload_shadow_disable(TIMER6);
    timer_enable(TIMER6);
}

/* Less than 3 us is not accurate */
void delay_us(uint16_t us)
{
    for (TIMER_CNT(TIMER6) = 0; TIMER_CNT(TIMER6) < us;)
    {
    }
}

void delay_ms(uint16_t ms)
{
    while (ms--)
    {
        delay_us(1000);
    }
}

/*!
    \brief      delay decrement
    \param[in]  none
    \param[out] none
    \retval     none
*/
void delay_decrement(void)
{
    if (0U != delay){
        delay--;
    }
}
